﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using AutoMapper;
using KeyCore.Domain.Model;
using KeyCore.Framework.Contexts;
using KeyCore.Framework.Repositories;
using KeyCore.Loans.Client.Web.Models.LoansClient;
using Microsoft.Web.Mvc;
using MvcContrib.Attributes;

namespace KeyCore.Loans.Client.Web.Controllers
{

    [Authorize]
    public class LoansClientController : Controller
    {

    protected LoansClientRegisterWizardModel  _dataWizard; 

        //
        // GET: /LoansClient/
        public ActionResult Index()
        {
            var wizard  =  new LoansClientRegisterWizardModel();
            wizard.Initialize();
            return View(wizard);

            //using (var crepo = new LoansClientRepository())
            //{
            //    //if (crepo.ClientExist)
            //    //{
            //    //    if (crepo.ClientPersonalDataExist)
            //    //        return RedirectToAction("Index", "Home");
            //    //    return RedirectToAction("CreateLoansClientPersonalData", "LoansClient");
            //    //}
            //    return RedirectToAction("CreateLoansClient", "LoansClient");
            //}
            
        }

        [HttpPost]
        public ActionResult Index([Deserialize] LoansClientRegisterWizardModel wizard, ILoansClientWizardStep step)
        {
            wizard.Steps[wizard.CurrentStepIndex] = step;
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(Request["next"]))
                {
                    wizard.CurrentStepIndex++;
                }
                else if (!string.IsNullOrEmpty(Request["prev"]))
                {
                    wizard.CurrentStepIndex--;
                }
                else
                {
                    // TODO: we have finished: all the step partial
                    // view models have passed validation => map them
                    // back to the domain model and do some processing with
                    // the results

                    return Content("thanks for filling this form", "text/plain");
                }
            }
            else if (!string.IsNullOrEmpty(Request["prev"]))
            {
                // Even if validation failed we allow the user to
                // navigate to previous steps
                wizard.CurrentStepIndex--;
            }

            return View(wizard);
        }

        [HttpPost]
        public ActionResult CreateLoansClient(LoansClientBasicDataModel model)
        {
          //  using (var crepo = new LoansClientRepository())
          //  {

          //      var userId = (Guid) Membership.GetUser().ProviderUserKey;
          //      // check if client exist if not create
          //      if (!crepo.ClientExist)
          //      {
          //          var client = new LoansClient();
          // //         Mapper.CreateMap<LoansClientCreateModel, LoansClient>();
          ////          client = Mapper.Map<LoansClientCreateModel, LoansClient>(model);
          //          client.OsobaId = crepo.ClientId;
          //          crepo.CreateLoansClient(client);
          //          return RedirectToAction("Index", "LoansClient");
          //      }
          //  }

            return View();
        }

        // Strp 1
        [HttpPost]
        public ActionResult CreateLoansClientBasicData(string nextButton)
        {
            if (nextButton != null)
            {
                return RedirectToAction("CreateLoansClientPersonalData");
            }

            return View(_dataWizard);
            //using (var crepo = new LoansClientRepository())
            //{

            //    var userId = (Guid) Membership.GetUser().ProviderUserKey;
            //    // check if client exist if not create
            //    if (!crepo.ClientPersonalDataExist)
            //    {
            //        var client = new LoansClient();
            //        Mapper.CreateMap<LoansClientPersonalDataModel, LoansClient>();
            //        client = Mapper.Map<LoansClientPersonalDataModel, LoansClient>(model);
            //        client.OsobaId = crepo.ClientId;
            //        crepo.CreateLoansClient(client);
            //        return RedirectToAction("Index", "LoansClient");
            //    }
            //}
        }

        // Step 2
        [HttpPost]
        public ActionResult CreateLoansClientPersonalData(string backButton, string nextButton)
        {
            if (backButton != null)
            {
                return RedirectToAction("CreateLoansClientBasicData");
            }
            else if (nextButton != null)
            {
                return RedirectToAction("Confirm");
            }
            return View(_dataWizard);
        }

        public ActionResult Confirm(string backButton, string confirmButton)
        {
            if (backButton != null)
            {
                return RedirectToAction("CreateLoansClientPersonalData");
            }
            else if (confirmButton != null)
            {
                return RedirectToAction("Complete");
            }
            return View(_dataWizard);
        }

        public ViewResult Complete()
        {
            return View(_dataWizard);
        }

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }

        protected override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            base.OnResultExecuting(filterContext);
        }
    }


    public static class AutoM
    {
        public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>(
            this IMappingExpression<TSource, TDestination> expression)
        {
            var sourceType = typeof (TSource);
            var destinationType = typeof (TDestination);
            var existingMaps = Mapper.GetAllTypeMaps().First(x => x.SourceType.Equals(sourceType)
                                                                  && x.DestinationType.Equals(destinationType));
            foreach (var property in existingMaps.GetUnmappedPropertyNames())
            {
                expression.ForMember(property, opt => opt.Ignore());
            }
            return expression;
        }


        public static void CreateMapForEF<TDto, TEntity>()
        {
            Mapper.CreateMap<TDto, TEntity>()
                  .ForAllMembers(o => o.Condition(ctx =>
                                                      {

                                                          var members = ctx.Parent.SourceType.GetMember(ctx.MemberName);
                                                              // get the MemberInfo that we are mapping

                                                          if (!members.Any())
                                                              return false;

                                                          if (members.First().GetCustomAttributes(
                                                              typeof (EdmRelationshipNavigationPropertyAttribute), false)
                                                                     .Any())
                                                              return false;

                                                          return
                                                              members.First()
                                                                     .GetCustomAttributes(
                                                                         typeof (EdmScalarPropertyAttribute), false)
                                                                     .Any();
                                                              // determine if the Member has the EdmScalar attribute set

                                                      }));
        }
    }
}
